package com.ciban.smarthome.module.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DbBaseDao {

	protected String tableName;

	protected SQLiteDatabase db;

	private DatabaseManager manger;

	public DbBaseDao(Context context){
		initDbManger(context);
	}

	protected DbBaseDao(Context context, String tableName) {
		initDbManger(context);
		this.tableName = tableName;
	}


	protected void exec(String sql){
		db=manger.openDatabase();
		db.execSQL(sql);
		closeDb();
	}

	/**
	 * 提供对多表联合查询的操作，需要用完以后 手动方法关闭数据库
	 * @param sql
	 * @param args
	 * @return
	 */
	public Cursor execRawQuery(String sql, String[] args){
		db=manger.openDatabase();
		return db.rawQuery(sql, args);
	}

	/**
	 * 初始化数据库管理类
	 * @param context
	 */
	private void initDbManger(Context context) {
		if (!manger.isInit()) {
			StandardDbHelper helper = new StandardDbHelper(context);
			manger.initializeInstance(helper);
		}
		manger = DatabaseManager.getInstance();
	}

	protected long insert(String nullColumnHack, ContentValues values) {
		long insert = -1;
		db = manger.openDatabase();
		if (db.isOpen()) {
			insert = db.insert(tableName, nullColumnHack, values);
		}
		closeDb();
		return insert;
	}

	protected int update(ContentValues values, String whereClause,
			String[] whereArgs) {
		int update = -1;
		db = manger.openDatabase();
		if (db.isOpen()) {
			update = db.update(tableName, values, whereClause, whereArgs);
		}
		closeDb();
		return update;
	}

	protected int del(String whereClause, String[] whereArgs) {
		int delete = -1;
		db = manger.openDatabase();
		if (db.isOpen()) {
			delete = db.delete(tableName, whereClause, whereArgs);
		}
		closeDb();
		return delete;
	}

	protected Cursor query(String[] columns, String selection,
			String[] selectionArgs, String order) {
		db = manger.openDatabase();
		return db.query(tableName, columns, selection, selectionArgs, null,
				null, order);
	}

	public void closeDb() {
		manger.closeDatabase();
	}
}
